package com.qiyun.dinghuohui.fragment;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.qiyun.dinghuohui.MainActivity;
import com.qiyun.dinghuohui.R;
import com.qiyun.dinghuohui.activity.GoodsDetailActivity;
import com.qiyun.dinghuohui.base.BaseFragment;
import com.qiyun.dinghuohui.common.ClientCookie;
import com.qiyun.dinghuohui.common.CommonDataSets;
import com.qiyun.dinghuohui.common.ImageUtils;
import com.qiyun.dinghuohui.pop.FreeSearchChangePop;
import com.qiyun.dinghuohui.pop.SxChangePop;
import com.qiyun.dinghuohui.utils.CommonUtil;
import com.qiyun.dinghuohui.utils.Inject;
import com.qiyun.dinghuohui.widget.AnimationUtils;
import com.qiyun.dinghuohui.widget.DividerItemDecoration;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by xlm on 2018\5\28 0028
 */

public class FreeOrderFragment extends BaseFragment {

    @Inject(R.id.unknown)
    private RelativeLayout mRelaUnknown;
    private boolean isSquare = false;

    @Inject(R.id.search)
    private RelativeLayout mRelaSearch;
    @Inject(R.id.normal)
    private RelativeLayout mRelaNormal;

    @Inject(R.id.recyclerview)
    private RecyclerView mRecycleView;
    @Inject(R.id.spuare)
    private RelativeLayout mRelaSquarel;//判断是否是网格列表
    @Inject(R.id.square_image)
    private ImageView mImagSquare;//切换网格图标
    @Inject(R.id.filter)
    private LinearLayout mLinearSx;

    private List<JSONObject> listGoods = new ArrayList<>();

    @Inject(R.id.part2)
    private RelativeLayout mRelaPart2;

    private int distance;


    @Inject(R.id.sort)
    private LinearLayout mLinearPop;
    @Inject(R.id.sort_change)
    private RelativeLayout mRelaSearchPopIcon;

    @Inject(R.id.normal)
    private RelativeLayout mRelaPopShow;//筛选按钮

    @Inject(R.id.search_btn)
    private RelativeLayout mSearchBtn;//搜索按钮
    @Inject(R.id.search_icon)
    private RelativeLayout mRelaIcon;

    @Inject(R.id.sort_choose)
    private LinearLayout mLineSearchPop;

    @Inject(R.id.edit_search)
    private AppCompatEditText mEditSearch;
    @Inject(R.id.search_option)
    private TextView mTextSearch;
    @Inject(R.id.num_money_k_s)
    private TextView mTxtOrderInfo;

    private boolean isSearch = false;

    private boolean isSort = false;
    private String serchFilter = "编号";//搜索条件


    @Override
    protected void onSetContentView() {
        setContentView(R.layout.fragment_freeorder);
    }

    @Override
    protected void initViews() {
        mRelaNormal.setVisibility(View.VISIBLE);
        mRelaSearch.setVisibility(View.GONE);
        mImagSquare.setSelected(false);
        mEditSearch.setHint("按编号搜索");
        mTextSearch.setText("编号");
        String cout = CommonDataSets.getOrderCount() + "件";
        String money = CommonDataSets.getOrdersMoney() + "元";
        String Kuan = CommonDataSets.getOrderKuan() + "款";
        String KColor = CommonDataSets.getOrderKColor() + "款色";
        String orderInfo = cout + " " + money + "  " + Kuan + " " + KColor;
        mTxtOrderInfo.setText(orderInfo);
    }

    @Override
    protected void onSetListener() {
        mLineSearchPop.setOnClickListener(getCurrentFragment());
        mRelaIcon.setOnClickListener(getCurrentFragment());
        mSearchBtn.setOnClickListener(getCurrentFragment());
        mLinearPop.setOnClickListener(getCurrentFragment());
        mRelaUnknown.setOnClickListener(getCurrentFragment());
        mRelaSquarel.setOnClickListener(getCurrentFragment());
        mLinearSx.setOnClickListener(getCurrentFragment());
        mRecycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                distance += dy;
                if (dy >= 0 && distance > 300) {
                    onScrolledUp();
                } else if (dy < 0) {
                    onScrolledDown();
                }
                if (distance == 0) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(mRecycleView.getLayoutParams());
                        lp.setMargins(0, CommonUtil.dip2px(35, getActivity()), 0, 0);
                        mRecycleView.setLayoutParams(lp);
                        mRelaPart2.setVisibility(View.VISIBLE);
                    }
                }
                if (distance >= CommonUtil.dip2px(35, getActivity())) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(mRecycleView.getLayoutParams());
                        mRecycleView.setLayoutParams(lp);
                        lp.setMargins(0, 0, 0, 0);
                    }
                }
            }
        });

    }


    public void onScrolledUp() {
        AnimationUtils.showAndHiddenAnimation(mRelaPart2, AnimationUtils.AnimationState.STATE_HIDDEN, 600);
    }

    public void onScrolledDown() {
        AnimationUtils.showAndHiddenAnimation(mRelaPart2, AnimationUtils.AnimationState.STATE_SHOW, 600);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.unknown:
                if (!isSearch) {
                    isSearch = true;
                    mRelaSearch.setVisibility(View.VISIBLE);
                    mRelaNormal.setVisibility(View.GONE);
                } else {
                    isSearch = false;
                    mRelaNormal.setVisibility(View.VISIBLE);
                    mRelaSearch.setVisibility(View.GONE);
                    freeOrderAdapter.setNewData(listGoods);
                }
                break;
            case R.id.spuare:
                if (!isSquare) {
                    isSquare = true;
                    mImagSquare.setSelected(true);
                    listGoods=mapToArray(listGoods);
                    setFreeOrderAdapter(false);
                } else {
                    isSquare = false;
                    mImagSquare.setSelected(false);
                    listGoods=mapToArray(listGoods);
                    setFreeOrderAdapter(true);
                }
                break;
            case R.id.filter:
                //切换drawer
                ((MainActivity) getActivity()).tooggleDrawer(getCurrentFragment());
                break;
            case R.id.sort:
                showFilterPop();
                if (mNumPop.getPopupWindow().isShowing()) {
                    mLinearPop.setSelected(true);
                }
                break;
            case R.id.search_btn:
                isSearch = true;
                mRelaSearch.setVisibility(View.VISIBLE);
                mRelaNormal.setVisibility(View.GONE);
                break;
            case R.id.search_icon:
                String text = mEditSearch.getText().toString();
                if (CommonUtil.isEmpty(text)) {
                    showToast("请输入" + serchFilter);
                } else {
                    //按照选择搜索
                    listGoods=getSearchGoodsByCode(text);
                    freeOrderAdapter.setNewData(listGoods);
                    if (listGoods.size() == 0) {
                        showToast("没有内容");
                    }
                    mEditSearch.setText("");
                    mRelaSearch.setVisibility(View.GONE);
                    mRelaNormal.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.sort_choose:
                showSearchPop();
                if (mSearchPop.getPopupWindow().isShowing()) {
                    mRelaSearchPopIcon.setSelected(true);
                }
                break;
        }
    }

    //搜索商品通过code
    private List<JSONObject> getSearchGoodsByCode(String code) {
        List<JSONObject> list = new ArrayList<>();
        for (JSONObject o : listGoods) {
            String goodsCode = o.optString("code");
            if (goodsCode.equals(code)) {
                list.add(o);
            }
        }
        if (list.size() == 0) {
            showToast("没找到该商品");
        }
        return list;
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
        listGoods = CommonDataSets.ds_goods;
        setFreeOrderAdapter(true);
    }

    private FreeSearchChangePop mSearchPop;

    private void showSearchPop() {
        if (mSearchPop == null) {
            mSearchPop = new FreeSearchChangePop(getActivity());
            mSearchPop.setFocusable(true);
            mSearchPop.setListener(new FreeSearchChangePop.Listener() {
                @Override
                public void onSelected(String filter) {
                    serchFilter = filter;
                    mEditSearch.setText("");
                    mEditSearch.setHint("按" + serchFilter + "搜索");
                    mTextSearch.setText(serchFilter);
                }
            });
            mSearchPop.getPopupWindow().setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    hidePop2();
                }
            });
        }
        mSearchPop.showAsDropDown(mRelaSearch);
    }


    private SxChangePop mNumPop;

    private void showFilterPop() {
        if (mNumPop == null) {
            mNumPop = new SxChangePop(getActivity());
            mNumPop.setFocusable(true);
            mNumPop.setListener(new SxChangePop.Listener() {
                @Override
                public void onSelected(String filter) {
                    freeOrderAdapter.setNewData(mapToArray(listGoods));
                    isSort = true;
                }
            });
            mNumPop.getPopupWindow().setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    hidePop();
                }
            });
        }
        mNumPop.showAsDropDown(mRelaPopShow);
    }

    private void hidePop() {
        mLinearPop.setSelected(false);
    }

    private void hidePop2() {
        mRelaSearchPopIcon.setSelected(false);
    }

    //商品信息转换为Array
    public List<JSONObject> mapToArray(List<JSONObject> listGoods) {
        Map<Integer, JSONObject> map = new TreeMap<>();
        for (JSONObject o : listGoods) {
            map.put(Integer.parseInt(o.optString("code")), o);
        }
        List<JSONObject> list = new ArrayList<>();
        for (Integer integer : map.keySet()) {
            JSONObject object = map.get(integer);
            list.add(object);
        }
        listGoods.clear();
        listGoods.addAll(list);
        return list;
    }

    private FreeOrderAdapter freeOrderAdapter;

    /**
     * 网格数据
     */
    private void setFreeOrderAdapter(boolean square) {
        if (square) {
            GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3,
                    LinearLayoutManager.VERTICAL, false);
            mRecycleView.setLayoutManager(gridLayoutManager);
            mRecycleView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.GRID_LIST,
                    getResources().getDrawable(R.drawable.shape_grid_div)));
            freeOrderAdapter = new FreeOrderAdapter(R.layout.item_square, listGoods);
        } else {
            LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
            mRecycleView.setLayoutManager(layoutManager);
            freeOrderAdapter = new FreeOrderAdapter(R.layout.item_list, listGoods);
        }
//        freeOrderAdapter.addHeaderView(createHederView());
        mRecycleView.setAdapter(freeOrderAdapter);
        freeOrderAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                GoodsDetailActivity.startActivity(getActivity(), listGoods.get(position));
            }
        });
    }

    //根据主界面回传的筛选信息，过滤商品
    public void filterOptions(Map<String, JSONObject> map) {
        showLoading("加载中...");
        listGoods = CommonDataSets.getSxDataByMap(map);
        freeOrderAdapter.setNewData(listGoods);
        mRecycleView.scrollToPosition(0);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                dismissLoading();
            }
        }, 1200);
        isSort = false;
    }

    private class FreeOrderAdapter extends BaseQuickAdapter<JSONObject, BaseViewHolder> {

        private int layOutId;

        public FreeOrderAdapter(int layoutResId, @Nullable List<JSONObject> data) {
            super(layoutResId, data);
            this.layOutId = layoutResId;
        }

        @Override
        protected void convert(BaseViewHolder helper, JSONObject item) {

            String count = item.optString("count");
            String sort = item.optString("code");
            String identifier = item.optString("goods_code");
            int goodsPicCount = item.optInt("image_url");
            int picu = item.optInt("picu");
            String imagUrl = null;
//            if (picu == 1) {
//                if (goodsPicCount > 0) {
//
//                }
//            }
//            imagUrl = ClientCookie.getServerUrl() + "/goods/img/" + sort + ".jpg";
            imagUrl = "https://gss0.bdstatic.com/94o3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike272%2C5%" +
                    "2C5%2C272%2C90/sign=46ef876d76d98d1062d904634056d36b/8d5494eef01f3a2945c7c45f9325bc315c607c17.jpg";
            switch (layOutId) {
                case R.layout.item_square:
                    int width = CommonUtil.getDisplayMetrics(getActivity()).widthPixels / 3;
//                  helper.itemView.getLayoutParams().height = width;
                    helper.itemView.getLayoutParams().width = width - 1;
//                  ImageUtils.showImage(getActivity(), (ImageView) helper.getView(R.id.square_image), imagUrl);
//                  helper.setVisible(R.id.square_tag,false);
//                    ImageUtils.showImage(getActivity(), (ImageView) helper.getView(R.id.square_image),
//                            ClientCookie.getServerUrl() + "/goods/img/" + imagUrl+ ".jpg");
                    ImageUtils.showImage(getActivity(), (ImageView) helper.getView(R.id.square_image),
                           ImageUtils.imagUrl);
                    helper.setText(R.id.square_num, count + "件");
                    helper.setText(R.id.square_sort, sort);
                    helper.setText(R.id.square_identifier, identifier);
                    break;
                case R.layout.item_list:
//                    ImageUtils.showImage(getActivity(), (ImageView) helper.getView(R.id.list_image),
//                            ClientCookie.getServerUrl() + "/goods/img/" + imagUrl + ".jpg");
                    ImageUtils.showImage(getActivity(), (ImageView) helper.getView(R.id.list_image),
                            ImageUtils.imagUrl);
                    helper.setText(R.id.list_num, count);
                    helper.setText(R.id.list_sort, sort);
                    helper.setText(R.id.list_identifier, identifier);
                    break;
            }
        }
    }
}
